import json
import re
import requests
from lxml import etree



class MySession(requests.Session):
    def request(self, *args, **kwargs):
        kwargs.setdefault('timeout', 5)
        return super(MySession, self).request(*args, **kwargs)


class AcquireInfoTotal(object):
    def __init__(self, pid):
        self.pid = pid
        get_params = {'id': str(pid)}

        self.headers = {
            "User-Agent":
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"
        }

        url_get = "http://10.68.1.38:8000/doqleiview/doqleiview.aspx"

        # self.users = requests.Session()
        self.users = MySession()

        get_basic_content = self.users.get(url_get,
                                           params=get_params,
                                           headers=self.headers)
        if get_basic_content.status_code != 200:
            raise Exception('网络访问失败')
        self.basic_html_doc = get_basic_content.text
        basic_tree = etree.HTML(self.basic_html_doc)

        self.basic_param_patient = basic_tree.xpath('//ul[@class="ztree"]')[0].attrib
        basic_param_code = basic_tree.xpath('//div[contains(@class, "model_menu_items")]')[0].attrib
        post_param_menu = {
            'type': self.basic_param_patient['data-type'],
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'idata[0].key': 'uhid',
            'idata[0].value': basic_param_code["data-uhid"],
            'idata[1].key': 'date_validated',
            'idata[1].value': self.basic_param_patient['data-date_validated'],
            'idata[2].key': 'treatment',
            'idata[2].value': basic_param_code["data-uhid"].split(']')[1],
        }
        url_menu = "http://10.68.1.38:8000/Menu/MedicalMenu"

        self.menu_json_data = self.users.post(url_menu,
                                              headers=self.headers,
                                              data=post_param_menu)
        if self.menu_json_data.status_code != 200:
            raise Exception('网络访问失败')

    def query_content(self, query_kind='病程记录'):

        menu_respond = self.menu_json_data.json()
        test_info_data = {}
        for i in menu_respond['Data']:

            test_info_data.update(i.setdefault('Data', {}))

            if i.setdefault('Text', '') == query_kind:
                mtype = i['Type']
                break
            if i.setdefault('Children', ''):
                for j in i['Children']:
                    test_info_data.update(j.setdefault('Data', {}))
                    if j.setdefault('Text', '') == query_kind:
                        mtype = j['Type']

                        break
                else:
                    continue
                break

        post_para_test = {
            'type': self.basic_param_patient['data-type'],
            'patientid': '☆',
            'snick': '',
            'mdata': self.basic_param_patient['data-mdata'],
            'integrationim': self.basic_param_patient['data-integrationim'],
            'inum': self.basic_param_patient['data-inum'],
            'patientname': self.basic_param_patient['data-patientname'],
            'official1': self.basic_param_patient['data-official1'],
            'mtype': mtype,
        }

        index_ = 0
        for k, v in test_info_data.items():
            post_para_test['idata[%s].key' % index_] = k
            post_para_test['idata[%s].value' % index_] = v
            index_ += 1

        url_result = "http://10.68.1.38:8000/Content/Index"

        try:

            result = self.users.post(
                url_result,
                headers=self.headers,
                data=post_para_test,

            ).text

        except requests.exceptions.ReadTimeout as e:

            result = ''
        # with open(f'{query_kind}.txt', 'w+', encoding='utf-8') as f:
        #     f.write(result)
        return {query_kind: result}


class DataResolver(object):
    def __init__(self, pid):
        self.patient_info = {}
        self.pid = pid
        self.result_list = []
        self.result_dic = ''

    # @staticmethod
    def do_table(self, html_grab):
        tree = etree.HTML(html_grab)
        tables = tree.xpath('//table')
        result_list = []
        for table in tables:
            table_dic = {}
            trs = table.findall('.//tr')
            table_dic['test_title'] = trs[0].find('.//td//input').attrib.get(
                'value').split('(')[0]
            test_date = trs[0].find('.//td//input').attrib.get('value').split(
                '(')[1]
            test_date = test_date.strip()
            test_date = test_date.strip(':')
            test_date = test_date.strip(')')
            table_dic['test_date'] = test_date
            table_dic['test_result'] = []
            for tr in trs[2:]:
                tds = tr.findall('.//td')
                result_details = {
                    'title':
                        tds[1].text,
                    'result':
                        tds[2].text.strip(),
                    'note':
                        tds[3].find('./font').text,
                    'flag':
                        '升高' if tds[3].find('./font').text == '↑' else
                        ('降低' if tds[3].find('./font').text == '↓' else '正常'),
                    'normal':
                        tds[4].text,
                }

                table_dic['test_result'].append(result_details)
            result_list.append(table_dic)
        self.result_list = result_list
        return result_list

    @staticmethod
    def do_test(test_result):
        result_dic = {}
        with open('.\\myjson\\spliter.json', 'r', encoding='utf-8') as load_f:
            load_dic = json.load(load_f)

        for each_test_dic in test_result:

            for k_test in load_dic.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[
                            k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key in load_dic[k_test].keys():
                            if each_test_key in each_test_result["title"]:
                                if each_test_result["flag"] in load_dic[
                                    k_test][each_test_key].keys():
                                    result_dic[k_test][
                                        each_test_dic["test_date"]].append({
                                        "项目":
                                            each_test_result["title"],
                                        "结果":
                                            "%s %s" %
                                            (each_test_result["result"],
                                             load_dic[k_test][each_test_key]
                                             ["单位"]),
                                        "提示":
                                            load_dic[k_test][each_test_key][
                                                each_test_result["flag"]]
                                    })

        with open('.\\myjson\\test_analysis.json', 'r', encoding='utf-8') as load_f:
            test_load = json.load(load_f)
        for each_test_dic in test_result:

            for k_test in test_load.keys():
                if k_test in each_test_dic["test_title"]:
                    for each_test_result in each_test_dic["test_result"]:
                        if k_test not in result_dic.keys():
                            result_dic[k_test] = {}
                        if each_test_dic["test_date"] not in result_dic[
                            k_test].keys():
                            result_dic[k_test][each_test_dic["test_date"]] = []

                        for each_test_key_analysis in test_load[k_test].keys():
                            if each_test_key_analysis in each_test_result["title"]:

                                if each_test_result["result"] != test_load[k_test][each_test_key_analysis]:
                                    result_dic[k_test][
                                        each_test_dic["test_date"]].append({
                                        "项目":each_test_result["title"],
                                        "结果":each_test_result["result"],
                                        "提示":""
                                    })

        # result_string = '入院根据当前疫情防控及上级文件要求：查新型冠状病毒核酸检测示阴性。'
        result_string = ''
        for each_test_kind, each_test_kind_v in result_dic.items():
            if each_test_kind:
                result_string += '%s：' % each_test_kind

            for index_v, data_v in enumerate(each_test_kind_v.values()):
                if data_v:
                    if index_v > 0 and each_test_kind:
                        result_string += '%s：' % each_test_kind
                    normal = True

                    for each_data_dict in data_v:

                        result_string += '%s：%s ' % (each_data_dict['项目'],
                                                     each_data_dict['结果'])
                        if each_data_dict['提示']:
                            normal = False
                            result_string += '%s' % each_data_dict['提示']
                    if normal and each_test_kind in load_dic.keys():
                        result_string += '未见明显异常。'
                elif not data_v and each_test_kind:
                    result_string += "未见异常。"

        return result_string

    def record_resolve(self, html_dic):
        bcjl = html_dic.get('病程记录')
        if bcjl:
            tree = etree.HTML(bcjl)
            basic_info_td = tree.xpath('//div[@esttype="入院记录"]//table')[0].xpath(
                './/td//text()') if tree.xpath(
                '//div[@esttype="入院记录"]//table') else []
            for i in basic_info_td:
                i = i.strip()
                if i:
                    info_list = i.split("：")
                    try:
                        self.patient_info[info_list[0]] = info_list[1]
                    except IndexError as e:
                        info_list = i.split(":")
                        self.patient_info[info_list[0]] = info_list[1]

            self.patient_info["住院号"] = str(self.pid)
            self.patient_info["入院日期"] = self.patient_info.setdefault(
                '入院时间', '无信息').split()[0]
            self.patient_info["主诉"] = tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="5"]')[0].text if tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="5"]') else '无信息'

            self.patient_info["医师"] = tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="2"]')[0].text.split(
                "：")[1] if tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="2"]') else '无信息'
            self.patient_info["诊断"] = " ".join(
                tree.xpath('//div[@esttype="入院记录"]//span[@itemid="8"]'
                           )[0].xpath('string(.)').split()[1:] if tree.
                    xpath('//div[@esttype="入院记录"]//span[@itemid="8"]') else '无信息')
            self.patient_info["现病史"] = tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="6"]')[0].text if tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="6"]') else "无信息"
            self.patient_info["TPRBP"] = tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="10"]')[0].xpath(
                'string(.)') if tree.xpath(
                '//div[@esttype="入院记录"]//span[@itemid="10"]') else "无信息"
            # print(self.patient_info["TPRBP"])
            self.patient_info["入院体检"] = tree.xpath(
                '//div[@esttype="入院记录"]//p[@class="childmouseover"]'
            )[0].xpath('string(.)').strip() if tree.xpath(
                '//div[@esttype="入院记录"]//p[@class="childmouseover"]') else "无信息"
            self.patient_info["入院化验单"] = \
                tree.xpath('//div[@esttype="入院记录"]//p[@class="childmouseover"]/following-sibling::p/following-sibling::p//text()')[0] if tree.xpath(
                    '//p[@class="childmouseover"]/following-sibling::p/following-sibling::p//text()') else "无信息"
            self.patient_info["病人简介"] = tree.xpath(
                '//div[@esttype="首次病程记录"]//span[@itemid="1"]'
            )[0].text if tree.xpath(
                '//div[@esttype="首次病程记录"]//span[@itemid="1"]') else "无信息"
            self.patient_info[
                "入院情况出院记录"] = f"{self.patient_info['病人简介']} 以“{self.patient_info['主诉']}”入院。体格检查：{self.patient_info['TPRBP']}，{self.patient_info['入院体检']}"
            first_info_p = tree.xpath('//div[@esttype="首次病程记录"]//p')[1].xpath(
                'string(.)').strip() if tree.xpath(
                '//div[@esttype="首次病程记录"]//p') else '无信息'

            content_1 = re.findall(
                r".+病例特点(.*?)1(\.|、)(.+?)2(\.|、)(.*?)(查体|体格检查).+?", first_info_p,
                re.DOTALL)
            if content_1:
                self.patient_info['病例特点'] = content_1[0][2]
            content_2 = re.findall(
                r".+诊疗计划(.*?)1(\.|、)(.+?)2(\.|、)(.+?)3(\.|、)(.+?)4(\.|、)(.+)\d?",
                first_info_p, re.DOTALL)

            if content_2:
                self.patient_info['诊疗计划'] = content_2[0][2::2]

            self.patient_info['出院日期'] = tree.xpath(
                '//div[@esttype="出院记录"]//table')[0].xpath('.//td')[5].xpath(
                'string(.)').strip().split('：')[1].split()[0] if tree.xpath(
                '//div[@esttype="出院记录"]//table') else '无信息'
            self.patient_info['出院时间'] = tree.xpath(
                '//div[@esttype="出院记录"]//table')[0].xpath('.//td')[5].xpath(
                'string(.)').strip().split('：')[1] if tree.xpath(
                '//div[@esttype="出院记录"]//table') else '无信息'
            self.patient_info["出院诊断"] = tree.xpath(
                '//div[@esttype="出院记录"]//span[@itemid="1"]')[0].xpath(
                'string(.)') if tree.xpath(
                '//div[@esttype="出院记录"]//span[@itemid="1"]') else '无信息'
            self.patient_info["诊疗经过"] = tree.xpath(
                '//div[@esttype="出院记录"]//p')[4].xpath('string(.)').split(
                '：')[1] if tree.xpath('//div[@esttype="出院记录"]//p') else '无信息'
            self.patient_info["出院情况"] = tree.xpath(
                '//div[@esttype="出院记录"]//p')[6].xpath('string(.)').split(
                '：')[1] if tree.xpath('//div[@esttype="出院记录"]//p') else '无信息'

            self.patient_info["出院医嘱"] = tree.xpath(
                '//div[@esttype="出院记录"]//p')[7].xpath('string(.)').split(
                '：')[1] if tree.xpath('//div[@esttype="出院记录"]//p') else '无信息'

            self.patient_info["病史"] = '%s 患儿以“%s”为代主诉入院 查体：%s %s 初步诊断：%s 治疗：%s' % (
                self.patient_info.setdefault('入院时间', '').split()[1]
                if self.patient_info.setdefault('入院时间', '') else '无信息',
                self.patient_info.setdefault('主诉', '无信息'),
                self.patient_info.setdefault('TPRBP', '无信息'),
                self.patient_info.setdefault('入院体检', '无信息'),
                self.patient_info.setdefault('诊断', '无信息'),
                self.patient_info.setdefault('诊疗计划', '')[1]
                if self.patient_info.setdefault('诊疗计划', '') else '无信息',
            )
        # LIS报告单
        # lis_data = html_dic.get('LIS报告单')
        # if lis_data:
        #     result_lis = self.do_table(lis_data)

        #     result_lis = self.do_test(result_lis)

        #     self.patient_info['化验单'] = result_lis
        # else:
        #     # self.patient_info['化验单'] = '入院根据当前疫情防控及上级文件要求：查新型冠状病毒核酸检测示阴性。'
        #     self.patient_info['化验单'] = '无信息'
        # PACS报告单
        pacs_data = html_dic.get('PACS报告单')
        if pacs_data:
            result_pacs = self.do_pacs(pacs_data)
            self.patient_info['影像学'] = result_pacs
        else:self.patient_info['影像学'] = "无信息"
        return self.patient_info

    def check_keywords(self, html_dic, key_words):
        result = {}
        tree = etree.HTML(html_dic['病程记录'])
        for key_word in key_words:
            result[key_word] = {'results': []}
            for each in tree.xpath(f'//div[contains(@esttype, "{key_word}")]'):
                if each:

                    date_result = ' '.join(
                        each.xpath('p')[0].xpath('string(.)').split('\n')
                        [0].split()[:2])
                    name_result = each.xpath('p')[0].xpath('string(.)').split(
                        '\n')[0].split()[2]
                    record_result = each.xpath('p')[1].xpath('string(.)')
                    result[key_word]['results'].append({
                        'date_result':
                            date_result,
                        'name_result':
                            name_result,
                        'record_result':
                            record_result
                    })
                    basic_info_td = tree.xpath(
                        '//div[@esttype="入院记录"]//table')[0].xpath(
                        './/td//text()') if tree.xpath(
                        '//div[@esttype="入院记录"]//table') else []

                    basic_info = {}
                    for i in basic_info_td:
                        i = i.strip()
                        if i:
                            info_list = i.split("：")
                            basic_info[info_list[0]] = info_list[1]
                    result[key_word]['姓名'] = basic_info['姓名']
                    result[key_word]['性别'] = basic_info['性别']
                    result[key_word]['年龄'] = basic_info['年龄']
                    result[key_word]["住院号"] = str(self.pid)
                    result[key_word]["出院诊断"] = tree.xpath(
                        '//div[@esttype="出院记录"]//span[@itemid="1"]'
                    )[0].xpath('string(.)') if tree.xpath(
                        '//div[@esttype="出院记录"]//span[@itemid="1"]') else '无信息'
                    result[key_word]["医师"] = tree.xpath(
                        '//div[@esttype="入院记录"]//span[@itemid="2"]'
                    )[0].text.split("：")[1] if tree.xpath(
                        '//div[@esttype="入院记录"]//span[@itemid="2"]') else '无信息'
        return result

    def do_pacs(self, html_pacs):
        result = ''
        tree = etree.HTML(html_pacs)
        kind_list = tree.xpath(f'//input[@name="标本类型"]/@value')

        dio_list = tree.xpath(f'//input[@name="结论"]/@value')

        if kind_list and dio_list:
            kind_list = [x.split("()")[0] for x in kind_list]
            dio_list = [x.replace('\n', '') for x in dio_list]
            result_list = list(zip(kind_list, dio_list))
            result_list = ["：".join(x) for x in result_list]
            result = " ".join(result_list)

        return result



if __name__ == "__main__":
    line = 23041648
    result_json = {}
    a = AcquireInfoTotal(line)
    query_app = a.query_content(query_kind='LIS报告单')
    query_dic = query_app

    data_resolved = DataResolver(a.pid)
    data_resolved.record_resolve(query_dic)
    if data_resolved.patient_info:
        result_json[line] = data_resolved.patient_info

    x = data_resolved.result_list
    for i in x:
        print(i)
